<?php


namespace App\Controller\App;


use App\Base\BaseController4App;
use App\Entity\GiftLog;
use App\Entity\User;
use App\Repository\BannerRepository;
use App\Repository\GiftLogRepository;
use App\Repository\GiftRepository;
use App\Repository\MoneyRepository;
use App\Repository\SalesCutRepository;
use App\Repository\SalesUserJuanRepository;
use App\Repository\SiteOilCategoryRepository;
use App\Repository\SiteRepository;
use App\Repository\UserRepository;
use App\Service\MoneyService;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/app/gift")
 */
class AppGiftController extends BaseController4App
{
    /**
     * @Route("/list", name="AppGiftList")
     */
    public function AppGiftList(
        GiftRepository $giftRepository
    )
    {
        $req = $this->getRequestData();
        $page = $req["page"]??1;
        $data = $giftRepository->findBy(array("isOn"=>true),array("sort"=>"ASC"),10,$page * 10 - 10);
        return $this->json_out(1,"OK",$data);
    }

    /**
     * @Route("/buy", name="AppGiftBuy")
     */
    public function AppGiftBuy(
        GiftRepository $giftRepository,
        MoneyService $moneyService
    )
    {
        $user = $this->needToBeUser();
        $req = $this->getRequestData();
        $id = $req["id"]??1;
        $gift = $giftRepository->find($id);
        $money = $moneyService->getUserMoney($user);
        $jifen = $money["jifen"]??0;

        if ($jifen < $gift->getPrice()) {
            return $this->json_out(0,"积分余额不足");
        }

        //先扣钱
        $moneyService->mod($user,$gift->getPrice() * -1,2,211,"兑换礼品{$gift->getName()}",["id"=>$gift->getId()]);

        //再写日志
        $log = new GiftLog();
        $log->setCreateAt(new \DateTime())
            ->setUser($user)
            ->setStatus(1)
            ->setGift($gift);
        $this->myEm()->persist($log);
        $this->myEm()->flush();

//        dump($money);
        return $this->json_out(1,"兑换成功");
    }

    /**
     * @Route("/my", name="AppGiftMy")
     */
    public function AppGiftMy(
        GiftLogRepository $giftLogRepository
    )
    {
        $user = $this->needToBeUser();
        $req = $this->getRequestData();
        $page = $req["page"]??1;
        $log = $giftLogRepository->findBy(array("user"=>$user),array("id"=>"desc"),10,$page*10-10);
        $this->setGroups("app","gift");
        return $this->json_out(1,"数据获取成功",$log);
    }

}